package com.jiangchuang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiangchuang.domain.MinioProperties;
import com.jiangchuang.domain.entity.*;
import com.jiangchuang.domain.response.GetDishByIdRes;
import com.jiangchuang.domain.response.GetUnCheckedImgRes;
import com.jiangchuang.mapper.*;
import com.jiangchuang.service.IDishService;
import com.jiangchuang.utils.CommonUtils;
import com.jiangchuang.utils.Global;
import com.jiangchuang.utils.MinIoUtil;
import com.jiangchuang.utils.UserContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

@Service
@Slf4j
public class DishServiceImpl implements IDishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private StepMapper stepMapper;
    @Autowired
    private WxsecurityTraceMapper wxsecurityTraceMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAdminMapper adminMapper;
    @Resource
    private MinioProperties minioProperties;
    @Autowired
    private ViolateUserMapper violateUserMapper;
    @Autowired
    private WxsecurityTraceMapper traceMapper;
    @Autowired
    private DishIngredientMapper dishIngredientMapper;

    @Override
    public PageInfo<Dish> getDishesPage(Integer reviewStatus, int pageNo, int pageSize) {
        List<Dish> dishes = new ArrayList<>();
        PageHelper.startPage(pageNo,pageSize);
        if(reviewStatus==null){
            dishes = dishMapper.selectList(null);
        }else{
            QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
            dishQueryWrapper.eq("review_status", reviewStatus);
            dishes = dishMapper.selectList(dishQueryWrapper);
        }

        return new PageInfo<>(dishes);
    }

    @Override
    public PageInfo<Dish> getUnCheckedDishes(int pageNo, int pageSize) {
        List<Dish> dishes = new ArrayList<>();
        PageHelper.startPage(pageNo,pageSize);
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        // 4：人工审核通过， 查询所有未审核通过的数据
        dishQueryWrapper.ne("review_status", 4);
        dishQueryWrapper.ne("review_status", 3);
        dishes = dishMapper.selectList(dishQueryWrapper);
        return new PageInfo<>(dishes);
    }

    @Override
    public PageInfo<GetUnCheckedImgRes> getUnCheckedImg(int pageNo, int pageSize) {
        List<GetUnCheckedImgRes> traces;
        PageHelper.startPage(pageNo,pageSize);
        traces = wxsecurityTraceMapper.getUnCheckedImg();
        return new PageInfo<>(traces);
    }

    @Transactional
    @Override
    public void reviewDish(Integer tblType, Integer id, Integer reviewStatus) {
        switch (tblType){
            case 0:
                QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
                dishQueryWrapper.eq("id", id);
                Dish dish = dishMapper.selectOne(dishQueryWrapper);
                User user = userMapper.selectById(dish.getUid());
                if(reviewStatus==3){
                    // 菜品封面图
                    String path = dish.getCover().replace("https://sanshipu.jianguijizhang.com/minio/"+minioProperties.getBucketName(),"");
                    // 违规提示图
                    InputStream inputStream = null;
                    try {
                        inputStream = CommonUtils.downloadImg("https://sanshipu.jianguijizhang.com/minio/fanquan/static/imgViolation.png");
                    } catch (IOException e) {
                        throw new RuntimeException("违规警告图片下载失败"+e);
                    }

                    MinIoUtil.upload(minioProperties.getBucketName(), path, inputStream);

                    // 违规信息存入违规用户表
                    ViolateUser violateUser = new ViolateUser();
                    violateUser.setUid(user.getId());
                    violateUser.setNickname(user.getNickname());
                    violateUserMapper.insert(violateUser);
                }
                // 通过修改审核状态为“图像已审核”,否则改为“审核未通过”
                dish.setReviewStatus(reviewStatus);
                dishMapper.updateById(dish);

                QueryWrapper<WxsecurityTrace> traceQueryWrapper = new QueryWrapper<>();
                traceQueryWrapper.eq("img_url", dish.getCover());
                wxsecurityTraceMapper.delete(traceQueryWrapper);

                break;
            default:
                break;
        }
    }

    @Override
    public GetDishByIdRes getDishById(Integer did) {
        GetDishByIdRes res = dishMapper.getDishById(did);
        if(res==null) {
            return null;
        }
        QueryWrapper<Step> stepQueryWrapper = new QueryWrapper<>();
        stepQueryWrapper.eq("did",did);
        stepQueryWrapper.orderByAsc("step_num");
        List<Step> steps = stepMapper.selectList(stepQueryWrapper);
        res.setSteps(steps);

        return res;
    }

    @Override
    public PageInfo<Dish> getUserDishPage(Integer uid, Integer pageNo, Integer pageSize) {
        List<Dish> dishes = new ArrayList<>();
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.eq("uid",uid);
        PageHelper.startPage(pageNo,pageSize);
        dishes = dishMapper.selectList(dishQueryWrapper);
        return new PageInfo<>(dishes);
    }

    @Override
    public void deleteDishInfo(Integer did) {
        // 1.删除步骤
        QueryWrapper<Step> stepQueryWrapper = new QueryWrapper<>();
        stepQueryWrapper.eq("did", did);
        Dish dish = dishMapper.selectById(did);
        // 从html中提取img链接
        if (dish.getStep() != null) {
            Document stepHtml = Jsoup.parse(dish.getStep());
            Set<String> imgSrcs = extractImageSrcs(stepHtml);
            for (String stepUrl : imgSrcs) {
                // 删除步骤图片
                MinIoUtil.deleteFile(stepUrl);

                // 删除审核表中对应数据
                QueryWrapper<WxsecurityTrace> traceQueryWrapper = new QueryWrapper<>();
                traceQueryWrapper.eq("img_url", stepUrl);
                List<WxsecurityTrace> list = traceMapper.selectList(traceQueryWrapper);
                for (WxsecurityTrace trace : list) {
                    traceMapper.deleteById(trace.getId());
                }
            }
        }

        // 2.删除封面图
        if (StringUtils.isNotEmpty(dish.getCover())) {
            MinIoUtil.deleteFile(dish.getCover());

            // 删除审核表中对应数据
            QueryWrapper<WxsecurityTrace> traceQueryWrapper = new QueryWrapper<>();
            traceQueryWrapper.eq("img_url", dish.getCover());
            List<WxsecurityTrace> list = traceMapper.selectList(traceQueryWrapper);
            for (WxsecurityTrace trace : list) {
                traceMapper.deleteById(trace.getId());
            }
        }

        // 3.删除关联食材
        QueryWrapper<DishIngredient> dishIngredientQueryWrapper = new QueryWrapper<>();
        dishIngredientQueryWrapper.eq("did", did);
        dishIngredientMapper.delete(dishIngredientQueryWrapper);

        dishMapper.deleteById(did);

    }

    //提取HTML文档中的img标签的src属性
    static Set<String> extractImageSrcs(Document doc) {
        Set<String> imageSrcs = new HashSet<>();
        Elements imgs = doc.select("img"); // 查找所有的img标签
        for (Element img : imgs) {
            String src = img.attr("src"); // 提取src属性
            if (!src.isEmpty()) {
                imageSrcs.add(src);
            }
        }
        return imageSrcs;
    }
}
